package com.bridgetree.jubaocrm.ui.groups;

import java.util.Calendar;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.bridgetree.jubaocrm.R;
import com.bridgetree.jubaocrm.model.CRMUserBaseInfo;
import com.bridgetree.jubaocrm.service.JsonObjectPostRequest;
import com.bridgetree.jubaocrm.service.Network;
import com.bridgetree.jubaocrm.ui.Contents;
import com.bridgetree.jubaocrm.ui.LoginUtil;
import com.bridgetree.jubaocrm.ui.ProgressDialogUtil;
import com.bridgetree.jubaocrm.util.Groups;
import com.bridgetree.jubaocrm.util.LoginError;
/**
 *添加公告
 */
public class GroupsAddGongGaoActivity extends Activity {
	private final String TAG ="GroupsAddGongGaoActivity";
	private Context mContext;
	private Groups mGroups;
	private EditText group_addedit_title;
	private Button group_addedit_time;
	private EditText group_addedit_context;
	public static String peopleName ="";
	private InputMethodManager mInputMethodManager ;
	private String user_id =""; 
	private String token ="";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.group_announcement_addedit);
		mContext=this;

		peopleName ="";

		Intent intent = getIntent();
		if (intent == null) {
			Log.e(TAG, "intent is null");
			return;
		}
		mInputMethodManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);

		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
		user_id = prefs.getString(Contents.KEY_PERSONAL_LOGIN_USEID, ""); 
		token = prefs.getString(Contents.KEY_PERSONAL_LOGIN_TAKEN, "");

		group_addedit_title =(EditText)findViewById(R.id.group_addedit_title);
		group_addedit_time =(Button)findViewById(R.id.group_addedit_time);
		group_addedit_context =(EditText)findViewById(R.id.group_addedit_context);
		if(intent.getExtras()!=null){
			mGroups = (Groups)intent.getExtras().getSerializable("groupsMain");
		}

		findViewById(R.id.xm_bj_RelativeLayout_back).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
//				imm.hideSoftInputFromWindow(getCurrentFocus()
//						.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//				imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS); 
				imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); //强制隐藏键盘  
				finish();
			}
		});

		findViewById(R.id.xm_bj_bt_ok).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
//				imm.hideSoftInputFromWindow(getCurrentFocus()
//						.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//				imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS); 
				imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); //强制隐藏键盘  
				getAddGongGao();
			}
		});
		
		Calendar c = Calendar.getInstance();  
		int year = c.get(Calendar.YEAR); 
		int month = c.get(Calendar.MONTH); 
		int day = c.get(Calendar.DAY_OF_MONTH);
		group_addedit_time.setText(year+"-"+(month+2)+"-"+day);
		
		group_addedit_time.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				selectDate();
			}
		});
	}
	
	String date="";
	Dialog Datedialog = null;
	private void selectDate() {
		Calendar calendar = Calendar.getInstance();
		DatePickerDialog.OnDateSetListener dateListener = new DatePickerDialog.OnDateSetListener() {
			@Override
			public void onDateSet(DatePicker datePicker, int year, int month,
					int dayOfMonth) {
				date =year+"-"+(month+1)+"-"+dayOfMonth;
				group_addedit_time.setText(date);
			}
		};
		Datedialog = new DatePickerDialog(this, dateListener,
				calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
				calendar.get(Calendar.DAY_OF_MONTH));
		Datedialog.show();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			if (getCurrentFocus() != null
					&& getCurrentFocus().getWindowToken() != null) {
				mInputMethodManager.hideSoftInputFromWindow(getCurrentFocus()
						.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
			}
		}
		return super.onTouchEvent(event);
	}

	private void openDailog(String title, final String content) {
		new AlertDialog.Builder(mContext).setTitle(title)
		.setMessage(content).setPositiveButton("确定", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				if (content != null && content.trim().equals("用户不存在")) {
					// finish();
				}
				if("登陆失效，需重新登陆".equals(content) || "join(f.username.errors)".equals(content)){
					LoginUtil.executeLoginFaild(mContext);
				}

			}
		}).show();
	}

	private void getAddGongGao() {
		String tip ="";
		String title = group_addedit_title.getText().toString();
		if(title.equals("")){
			tip ="标题必须输入\n";
		}else{
			if(title.length()<5 || title.length()>150){
				tip +="公告标题必须是5-150个字符\n";
			}
		}
		
		String time =group_addedit_time.getText().toString();
		if(time.equals("")){
			tip +="时间必须选择\n";
		}
		
		String context =group_addedit_context.getText().toString();
		if(context.equals("")){
			tip +="公告内容不能为空\n";
		}else{
			if((context.length()<5) || context.length()>250){
				tip +="公告内容必须是5-250个字符\n";
			}
		}
		Network mNetword = new Network(mContext);
		if (!mNetword.isNetworkConnected()) {
			openDailog("网络提示", "网络未连接,请连接网络！");
		} else if (!tip.equals("")) {
			openDailog("错误提示", tip);
		} else {
			final ProgressDialog progressDialog = ProgressDialog.show(mContext,
					"网络数据", "...Loading...");
			
			//http://crmsoap.woniuwo.cn/group/info/new
			//gid=5374724ed5ac700e4ce8f609&title=12asfdasdfasfas&content=Adfsadfasdfasdfadf&
//=2014-06-22&user_id=cd34350bb2844077bfbd4abe5ec56f99
		//&token=15f4b0826dc841198c30088f4a7afd90
			//&validation=gAJ9cQAoVQZsb2NhbGVxAVUFemhfQ05xAl
			HashMap<String, String> mMap = new HashMap<String, String>();
			mMap.put("gid", mGroups.getGroup_id());
			mMap.put("title", title);
			mMap.put("content", context);
			mMap.put("expire_date", time);
			mMap.put("user_id", user_id);
			mMap.put("token", token);
			mMap.put("validation", CRMUserBaseInfo.kValication);
			String URL = Network.API_DOMAIN+"/group/info/new";

			RequestQueue requestQueue = Volley.newRequestQueue(mContext);
			JsonObjectPostRequest jsonObjectPostRequest = new JsonObjectPostRequest(
					URL, new Response.Listener<JSONObject>() {

						@Override
						public void onResponse(JSONObject response) {
							try {
								System.out.println("添加公告 "+response.toString());
								ProgressDialogUtil.dissmis(progressDialog);
								if (!response.isNull("errors")) {
									String errors = response.get("errors").toString();
									if (errors.equals("[]")) {
										finish();
									} else {
										org.json.JSONArray jsonArr;
										if (!response.isNull("errors")) {
											LoginError mLoginError = new LoginError();
											jsonArr = response.getJSONArray("errors");
											if (jsonArr.length() > 0) {
												for (int i = 0; i < jsonArr.length(); i++) {
													JSONObject jsonObj2 = jsonArr.getJSONObject(i);
													if (!jsonObj2.isNull("desc")) {
														String desc = jsonObj2.getString("desc");
														openDailog("失败提示", desc);
														mLoginError.setDesc(desc);
													}
													if (!jsonObj2.isNull("value")) {
														String value = jsonObj2.getString("value");
														mLoginError.setValue(value);
													}
												}
											}
										}
									}
								}
							} catch (JSONException e) {
								ProgressDialogUtil.dissmis(progressDialog);
								e.printStackTrace();
							}
						}
					}, new Response.ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError error) {
							if (progressDialog.isShowing()
									&& progressDialog != null) {
								progressDialog.dismiss();
							}
							Toast.makeText(mContext, "网络未连接！",
									Toast.LENGTH_LONG).show();
						}
					}, mMap);
			requestQueue.add(jsonObjectPostRequest);
		}

	}

}